﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
using IBuy.DataAccessLayer;
using System.Data;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
using IBuy.Entity;

namespace IBuy.Entity
{
    [Serializable]
    public class Product:IProduct
    {
        #region 私有成员
        private int productID;
        private string companyName;
        private string name;
        private string type;
        private float price;
        private int stock;
        private int delivery;
        private IDatabase database;
        #endregion

        #region 公有属性
        public int ProductionID
        {
            get { return productID; }
            set { productID = value; }
        }
        /// <summary>
        /// 公司名
        /// </summary>
        public string CompanyName
        {
            get { return companyName; }
            set { companyName = value; }
        }
        /// <summary>
        /// 名称
        /// </summary>
        public string Name
        {
            get
            {
                return name;
            }
            set
            {
                name = value;
            }
        }
        /// <summary>
        /// 种类
        /// </summary>
        public string Type
        {
            get
            {
                return type;
            }
            set
            {
                type = value;
            }
        }
        /// <summary>
        /// 价格
        /// </summary>
        public float Price
        {
            get
            {
                return price;
            }
            set
            {
                price = value;
            }
        }
        /// <summary>
        /// 库存
        /// </summary>
        public int Stock
        {
            get
            {
                return stock;
            }
            set
            {
                stock = value;
            }
        }
        /// <summary>
        /// 发货时间
        /// </summary>
        public int Delivery
        {
            get
            {
                return delivery;
            }
            set
            {
                delivery = value;
            }
        }
        #endregion

        #region 公有方法
        public Product()
        {
            DatabaseFactory databaseFactory = new OledbDatabaseFactory();
            database = databaseFactory.GetDatabase();
        }

        public bool InsertGoods(Hashtable values)
        {
            if (database.Insert("GOODS", values))
            {
                MessageBox.Show("插入物品成功！");
                return true;
            }
            else
            {
                MessageBox.Show("插入物品失败！");
                return false;
            }
        }

        public bool UpdateGoods(Hashtable columns, string where)
        {
            if (database.Update("GOODS", columns, where))
            {
                MessageBox.Show("更新物品成功！");
                return true;
            }
            else
            {
                MessageBox.Show("更新物品失败！");
                return false;
            }
        }

        public bool DeleteGoods(string name)
        {
            string where = " where NAME='" + name + "'";
            if (database.Delete("GOODS", where))
            {
                MessageBox.Show("删除物品成功！");
                return true;
            }
            else
            {
                MessageBox.Show("删除物品失败！");
                return false;
            }
        }

        public  Product GetProductByID(int id)
        {
            string where = " where GOODSID=" + id.ToString() ;
            DataRow row = GetDataSet(where).Tables[0].Rows[0];
            Product p = new Product();
            try
            {
                p.CompanyName = row[0].ToString();
                p.Type = row[1].ToString();
                p.Name = row[2].ToString();
                p.Price = Convert.ToSingle(row[3].ToString());
                p.Stock = Convert.ToInt32(row[4].ToString());
                p.Delivery = Convert.ToInt32(row[5].ToString());
                p.ProductionID = Convert.ToInt32(id);
            }
            catch (Exception e)
            {
                p = null;
            }
            return p;
        }
        #region 
        public DataSet GetGoodsByName(string name)
        {
            string where = "where NAME like '%" + name + "%'";
            return GetDataSet(where);
        }

        public DataSet GetGoodsByType(string type)
        {
            string where = "where TYPENAME like '%" + type + "%'";
            return GetDataSet(where);
        }

        public DataSet GetGoodsByCompanyName(string CompanyName)
        {
            string where = "where COMPANYNAME like '%" + CompanyName + "%'";
            return GetDataSet(where);
        }

        public DataSet GetGoodsByPrice(float price)
        {
            string where = "where PRICE=" + price;
            return GetDataSet(where);
        }

        public DataSet GetGoodsByStock(int stock)
        {
            string where = "where STOCK=" + stock;
            return GetDataSet(where);
        }

        public DataSet GetGoodsByDelivery(int delivery)
        {
            string where = "where DELIVERY=" + delivery;
            return GetDataSet(where);
        }

        public DataSet GetGoodsByPrice(float price, RangeType rangeType)
        {
            string where = GetQueryRange("PRICE", price, rangeType);
            return GetDataSet(where);
        }

        public DataSet GetGoodsByStock(int stock, RangeType rangeType)
        {
            string where = GetQueryRange("STOCK", stock, rangeType);
            return GetDataSet(where);
        }

        public DataSet GetGoodsByDelivery(int delivery, RangeType rangeType)
        {
            string where = GetQueryRange("DELIVERY", delivery, rangeType);
            return GetDataSet(where);
        }

        public DataSet GetGoodsByPrice(float min, float max)
        {
            string where = "where PRICE>=" + min + " and PRICE<=" + max;
            return GetDataSet(where);
        }

        public DataSet GetGoodsByStock(int min, int max)
        {
            string where = GetQueryRange("STOCK", min, max);
            return GetDataSet(where);
        }

        public DataSet GetGoodsByDelivery(int min, int max)
        {
            string where = GetQueryRange("DELIVERY", min, max);
            return GetDataSet(where);
        }

        private string GetQueryRange(string Item, int min, int max)
        {
            return "where " + Item + ">=" + min + " and " + Item + "<=" + max;

        }
        private string GetQueryRange(string Item, int value, RangeType rangeType)
        {
            string where = "";
            switch (rangeType)
            {
                case RangeType.EQUAL:
                    where = "where " + Item + "=" + value;
                    break;
                case RangeType.LESS:
                    where = "where " + Item + "<=" + value;
                    break;
                case RangeType.MORE:
                    where = "where " + Item + ">=" + value;
                    break;
            }
            return where;
        }
        private string GetQueryRange(string Item, float value, RangeType rangeType)
        {
            string where = "";
            switch (rangeType)
            {
                case RangeType.EQUAL:
                    where = "where " + Item + "=" + value;
                    break;
                case RangeType.LESS:
                    where = "where " + Item + "<=" + value;
                    break;
                case RangeType.MORE:
                    where = "where " + Item + ">=" + value;
                    break;
            }
            return where;
        }
        public DataSet GetNameAndIdOFAllGoods()
        {
            string SqlString = "select GOODSID,NAME from GOODS";
            return database.GetDataSet(SqlString);
        }
        #endregion
        public DataSet GetAllGoods()
        {
            return GetDataSet("");
        }

        private DataSet GetDataSet(string where)
        {
            string SqlString = "select COMPANYNAME,TYPENAME,NAME,PRICE,STOCK,DELIVERY,GOODSID from GOODSVIEW " + where;
            return database.GetDataSet(SqlString);
        }

        public Hashtable GetAllGoods(string colName)
        {
            string sql = "select GOODSVIEW." + colName + ", Count(GOODSVIEW." + colName + ") as Counts from GoodsView group by GOODSVIEW." + colName;
            DataSet dataset = database.GetDataSet(sql);
            DataTable table = dataset.Tables[0];
            Hashtable Goods = new Hashtable();
            foreach (DataRow row in table.Rows)
            {
                Goods.Add(row[0].ToString(), row[1].ToString());
            }
            return Goods;
        }

        public virtual bool BuyProducts(int productId, int count)
        {
            DatabaseFactory databaseFactory = new OledbDatabaseFactory();
            IDatabase dbs = databaseFactory.GetDatabase();
            string SqlString = "select STOCK from GOODS where GOODSID=" + productId.ToString();
            int stock = int.Parse(dbs.GetDataRow(SqlString)[0].ToString());
            if (stock - count<0)
            {
                throw new ApplicationException("商品"+productId.ToString()+"库存不足");
            }
            else
            {
                //将库存减少count
                SqlString = "update GOODS set STOCK=" + (stock - count).ToString() + " where GOODSID=" + productId.ToString();
                ArrayList sqlList = new ArrayList();
                sqlList.Add(SqlString);
                string saleString = "insert into SALES(GOODSID,GOODSCOUNT,SALEDATE) values("+productId+","+count.ToString()+",'"+DateTime.Now.Date.ToShortDateString()+"')";
                sqlList.Add(saleString);
                if (dbs.ExecuteSQL(sqlList))
                {
                    return true;
                }
                else
                {
                    throw new ApplicationException("数据库执行失败");
                }
            }
        }

        public virtual bool BuyProducts(List<Order> Sales)
        {
            DatabaseFactory databaseFactory = new OledbDatabaseFactory();
            IDatabase dbs = databaseFactory.GetDatabase();
            ArrayList sqlList = new ArrayList();
            foreach (Order item in Sales)
            {
                string SqlString = "select STOCK from GOODS where GOODSID=" + item.GoodsID.ToString();
                int stock = int.Parse(dbs.GetDataRow(SqlString)[0].ToString());
                if (stock - item.GoodsCount < 0)
                {
                    throw new ApplicationException("商品"+item.GoodsID.ToString()+"库存不足");
                }
                else
                {
                    //将库存减少count
                    SqlString = "update GOODS set STOCK=" + (stock - item.GoodsCount).ToString() + " where GOODSID=" + item.GoodsID.ToString();
                    sqlList.Add(SqlString);
                    string saleString = "insert into SALES(GOODSID,GOODSCOUNT,SALEDATE) values(" + item.GoodsID.ToString() + "," + item.GoodsCount.ToString() + ",'" + DateTime.Now.Date.ToShortDateString() + "')";
                    sqlList.Add(saleString);
                }
            }
            if (dbs.ExecuteSQL(sqlList))
            {
                return true;
            }
            else
            {
                throw new ApplicationException("数据库执行失败");
            }
        }

        public bool BuyProduct(int count)
        {
            string SqlString = "select STOCK from GOODS where GOODSID=" + productID.ToString();
            int stock = int.Parse(database.GetDataRow(SqlString)[0].ToString());
            if (stock < count)
            {
                return false;
            }
            else
            {
                //将库存减少count
                SqlString = "update GOODS set STOCK=STOCK-" + count.ToString() + " where GOODSID=" + productID.ToString();
                if (database.ExecuteSQL(SqlString) >= 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }
        #endregion
    }
    public enum RangeType{BETWING,EQUAL,MORE,LESS};
}
